package databases

import (
	"fly_export/global"
	po "fly_export/prometheus"
	"io"
	"log"
	"net/http"
	"strings"
	"time"

	"gorm.io/gorm"
)

type Alert struct {
	gorm.Model
	AlertName   string `json:"alertName"`
	AlertUrl    string `json:"alertUrl"`
	AlertFlieds string `json:"alertFlieds"` //告警字段
}

//	func NewAlerts() *alerts {
//		var alerts []alerts
//		return
//	}
func (a *Alert) TableName() string {
	return "alerts"
}

func (a Alert) Run() {
	var status int
	// fmt.Println(a.AlertUrl)
	begintime := time.Now()

	endtime := time.Now()
	elasped := endtime.Sub(begintime)
	resp, err := http.Get(a.AlertUrl)
	if err != nil {
		//panic(err)
		status = 300
	}
	respbody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println(err.Error())
	}
	log.Println("请求url：", a.AlertUrl, "返回值为：", string(respbody))
	if strings.Contains(string(respbody), a.AlertFlieds) {
		status = 200
	} else {
		status = 300
	}
	po.Updatestatus(global.GVA_ALERTLOAD, a.AlertUrl, a.AlertUrl, status, elasped)
	po.Updatetimes(global.GVA_ALERTLOAD2, a.AlertUrl, a.AlertUrl, status, elasped)
}
